import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sports_new/controller/navigation_logic.dart';
import 'package:sports_new/controller/match/list/lq_focus_logic.dart';
import 'package:sports_new/controller/match/list/lq_match_filter_logic.dart';
import 'package:sports_new/controller/match/list/match_page_logic.dart';
import 'package:sports_new/resources/styles.dart';
import 'package:sports_new/utils/constant.dart';
import 'package:sports_new/utils/user.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/view/loading/loading_match_list.dart';
import 'package:sports_new/view/match/basketball/lq_match_cell.dart';
import 'package:sports_new/widgets/loading/loading_widget.dart';
import 'package:sports_new/widgets/loading/no_data_widget.dart';
import 'package:umeng_apm_sdk/umeng_apm_sdk.dart';
import 'package:visibility_detector/visibility_detector.dart';

import '../../../utils/sp_utils.dart';
import '../../../widgets/ads_label.dart';
import '../../../widgets/header_delegate.dart';

class LqFocusView extends StatefulWidget {
  const LqFocusView({super.key});

  @override
  State<LqFocusView> createState() => _LqInterestViewState();
}

class _LqInterestViewState extends State<LqFocusView>
    with TickerProviderStateMixin {
  final logic =
      Get.put(LqFocusLogic(LqMatchType.focus, Constant.matchFilterTagFocus));
  final scrollC = ApmScrollController();
  final filter =
      Get.find<LqMatchFilterLogic>(tag: Constant.matchFilterTagFocus);
  @override
  void initState() {
    super.initState();
    scrollC.addListener(() {
      Get.find<NavigationLogic>().onMatchPageScroll();
    });
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<LqFocusLogic>(builder: (_) {
      return VisibilityDetector(
        key: const Key("interestKey"),
        onVisibilityChanged: (VisibilityInfo info) {
          logic.setVisible(!info.visibleBounds.isEmpty);
        },
        child: !logic.isLogin()
            ? NoDataWidget(
                tip: "登录后才能关注比赛",
                buttonText: "去登录",
                onTap: () => User.needLogin(() async {}))
            : Stack(
                children: [
                  EasyRefresh.builder(
                    controller: logic.refreshC,
                    header: Styles.refreshHeader(position: IndicatorPosition.locator),
                    onRefresh: () async {
                      Utils.onEvent('bspd_sx');
                      await logic.getMatch();
                    },
                    childBuilder: (BuildContext context, ScrollPhysics physics) =>
                    CustomScrollView(
                      physics: physics,
                      slivers: [
                        const HeaderLocator.sliver(),
                        if(SpUtils.matchLqAds?[4].hasValue == false ||
                            DateTime.now().difference(DateTime.parse(SpUtils.matchLqAds![4])).inHours > 24)
                          SliverToBoxAdapter(
                            child: AdsLabel(
                              adsTag: "match_lq_关注",
                              close: 4,
                              tapType: 'match_advertising',
                              tagParam: "关注",
                              margin: const EdgeInsets.fromLTRB(8, 8, 8, 0),
                              onClose: () => setState(() {}),
                            ),
                          ),
                        LoadingWidget<int>(
                          data: logic.originalData.length,
                          isLoading: logic.firstLoad,
                          noData: NoDataWidget.sliver(
                            tip: '暂无关注的比赛',
                            buttonText: '去关注',
                            onTap: () => Get.find<MatchPageLogic>().changeMatchTab(
                              Constant.matchFilterTagAll)
                          ),
                          loading: const LoadingMatchList.sliver(sportsId: 2),
                          child: () => const SliverToBoxAdapter(),
                        ),
                        if((logic.groupMatchList?.length ?? 0) > 0)
                          ...List.generate(
                              logic.dayList?.length ?? 0,
                                  (index) => SliverMainAxisGroup(
                                  slivers: [
                                    SliverPersistentHeader(
                                        pinned: true,
                                        delegate: HeaderDelegate(
                                            extent: 28,
                                            child: Styles.matchListGroupHeader(logic.dayList![index])
                                        )
                                    ),
                                    SliverList(
                                        delegate: SliverChildBuilderDelegate(
                                            childCount: logic.groupMatchList?[index].length ?? 0,
                                                (context, i) => LqMatchCell(logic.groupMatchList![index][i])
                                        )
                                    )
                                  ]
                              )
                          ),
                        SliverToBoxAdapter(
                          child: Container(height: 80),
                        )
                      ],
                    ),
                  ),
                  Styles.matchListBottomBar(
                      logic.hideMatchNum != 0 && !logic.isBottomHide,
                      logic.hideMatchNum, onClose: () {
                    Utils.onEvent('bspd_sxfc_gb');
                    logic.onCloseBottomBar();
                  }, onDefault: () {
                    Utils.onEvent('bspd_sxfc_hf');
                    logic.onSelectDefaultMatch();
                    // update();
                  })
                ],
              ),
      );
    });
  }
}
